package com.common.app.dialog

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.common.app.R
import com.common.app.data.bean.BaseCityModel
import com.common.app.data.repository.CommonPurposeApi
import com.common.app.databinding.DialogSelectThreeLevelAddressBinding
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.data.ListCommon
import com.common.base.utils.ToastUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getScreenHeight
import com.contrarywind.listener.OnItemSelectedListener
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import rxhttp.awaitResult
import rxhttp.toAwait
import rxhttp.wrapper.param.RxHttp

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：20/2/2023
 *
 * 描述：选择地区弹框
 *
 * 修订历史：
 *
 */
class SelectAddressThreeLevelDialog : Dialog, View.OnClickListener {
    private var binding: DialogSelectThreeLevelAddressBinding? = null

    /**
     *
     */
    private var mContext: Context? = null

    // 省级适配器数据
    private var provinceAdapter: ArrayWheelAdapter<*>? = null
    private var wheelListener_province_wv: OnItemSelectedListener? = null
    private var provinceItems = mutableListOf<BaseCityModel>()
    private var provinceItem: BaseCityModel? = null

    // 市级适配器数据
    private var cityAdapter: ArrayWheelAdapter<*>? = null
    private var wheelListener_city_wv: OnItemSelectedListener? = null
    private var cityItems = mutableListOf<BaseCityModel>()
    private var cityItem: BaseCityModel? = null

    // 镇区级适配器数据
    private var townshipAdapter: ArrayWheelAdapter<*>? = null
    private var wheelListener_township_wv: OnItemSelectedListener? = null
    private var townshipItems = mutableListOf<BaseCityModel>()
    private var townshipItem: BaseCityModel? = null

    /**
     * 点击回调
     */
    private var listener: OnSelectAddressThreeLevelListener? = null

    /**
     * 省市区三级联动
     */
    private var isThreeLevel = false
    private var isReset = false

    var provinceDisposable: Disposable? = null
    var cityDisposable: Disposable? = null
    var townshipDisposable: Disposable? = null

    var provinceTemp: String? = ""
    var cityTemp: String? = ""
    var townshipTemp: String? = ""

    constructor(context: Context) : super(context, R.style.VerticalDialog) {
        mContext = context
    }

    constructor(context: Context, isThreeLevel: Boolean) : super(context, R.style.VerticalDialog) {
        mContext = context
        this.isThreeLevel = isThreeLevel
    }

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {}
    protected constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogSelectThreeLevelAddressBinding.inflate(LayoutInflater.from(context))
        binding?.root?.let { setContentView(it) }

        binding?.let {
            it.selectCancelBtn.setOnClickListener(this)
            it.selectConfirmBtn.setOnClickListener(this)
        }

        binding?.let {

            //字体样式，默认是等宽字体
            it.provinceWv.setTypeface(Typeface.SANS_SERIF)
            it.cityWv.setTypeface(Typeface.SANS_SERIF)
            it.townshipWv.setTypeface(Typeface.SANS_SERIF)

            //设置滚轮文字大小
            it.provinceWv.setTextSize(17F)
            it.cityWv.setTextSize(17F)
            it.townshipWv.setTextSize(17F)

            //设置分割线的颜色
            it.provinceWv.setDividerColor(Color.LTGRAY)
            it.cityWv.setDividerColor(Color.LTGRAY)
            it.townshipWv.setDividerColor(Color.LTGRAY)

            // 设置分割线之间的文字的颜色
            it.provinceWv.setTextColorCenter(context.resources.getColor(R.color.text_content))
            it.cityWv.setTextColorCenter(context.resources.getColor(R.color.text_content))
            it.townshipWv.setTextColorCenter(context.resources.getColor(R.color.text_content))

            // 设置分割线以外文字的颜色
            it.provinceWv.setTextColorOut(Color.LTGRAY)
            it.cityWv.setTextColorOut(Color.LTGRAY)
            it.townshipWv.setTextColorOut(Color.LTGRAY)

            // 条目间距倍数
            it.provinceWv.setLineSpacingMultiplier(2F)
            it.cityWv.setLineSpacingMultiplier(2F)
            it.townshipWv.setLineSpacingMultiplier(2F)

            // 绑定适配器
            provinceAdapter = ArrayWheelAdapter(provinceItems)
            it.provinceWv.adapter = provinceAdapter // 设置显示数据
            it.provinceWv.currentItem = 0 // 初始化时显示的数据

            cityAdapter = ArrayWheelAdapter(cityItems)
            it.cityWv.adapter = cityAdapter // 设置显示数据
            it.cityWv.currentItem = 0 // 初始化时显示的数据

            townshipAdapter = ArrayWheelAdapter(townshipItems)
            it.townshipWv.adapter = townshipAdapter // 设置显示数据
            it.townshipWv.currentItem = 0 // 初始化时显示的数据


            it.provinceWv.setIsOptions(true)
            it.cityWv.setIsOptions(true)
            it.townshipWv.setIsOptions(true)

            it.provinceWv.setCyclic(false)
            it.cityWv.setCyclic(false)
            it.townshipWv.setCyclic(false)

            // 联动监听器
            wheelListener_province_wv = OnItemSelectedListener { index ->
                if (provinceItems.size > 0 && !TextUtils.isEmpty(provinceItems[index].code) && provinceItems.size > index) {
                    provinceItem = provinceItems[index]
                    queryAddress(provinceItem?.code, 1)
                }
            }
            // 添加联动监听
            it.provinceWv.setOnItemSelectedListener(wheelListener_province_wv)

            // 联动监听器
            wheelListener_city_wv = OnItemSelectedListener { index ->
                if (cityItems.size > 0 && !TextUtils.isEmpty(cityItems[index].code) && cityItems.size > index) {
                    cityItem = cityItems[index]
                    queryAddress(cityItem?.code, 2)
                }
            }
            // 添加联动监听
            it.cityWv.setOnItemSelectedListener(wheelListener_city_wv)

            // 联动监听器
            wheelListener_township_wv = OnItemSelectedListener { index ->
                if (townshipItems.size > 0 && !TextUtils.isEmpty(townshipItems[index].code) && townshipItems.size > index) {
                    townshipItem = townshipItems[index]
                }
            }
            // 添加联动监听
            it.townshipWv.setOnItemSelectedListener(wheelListener_township_wv)
        }

    }


    fun getDataList(): List<BaseCityModel> {
        return provinceItems
    }

    fun show(province: String?, city: String?, township: String?) {
        super.show()
        //设置弹框的高为屏幕的一半宽是屏幕的宽
        val mDialogLp = this.window?.attributes

        //设置宽度
//        mDialogLp?.width = ViewGroup.LayoutParams.MATCH_PARENT
        mDialogLp?.height = (getScreenHeight() * 0.4).toInt()

        mDialogLp?.gravity = Gravity.CENTER //设置dialog 在布局中的位置
        this.window?.attributes = mDialogLp
        window?.setWindowAnimations(R.style.bottomShowStyle) //添加动画:
        provinceTemp = province
        cityTemp = city
        townshipTemp = township
        initData()
    }


    override fun show() {
        super.show()
        //设置弹框的高为屏幕的一半宽是屏幕的宽
        val mDialogLp = this.window?.attributes

        //设置宽度
//        mDialogLp?.width = ViewGroup.LayoutParams.MATCH_PARENT
        mDialogLp?.height = (getScreenHeight() * 0.4).toInt()

        mDialogLp?.gravity = Gravity.CENTER //设置dialog 在布局中的位置
        this.window?.attributes = mDialogLp
        window?.setWindowAnimations(R.style.bottomShowStyle) //添加动画:

//        refreshProvinceData()

        initData()
    }

    private fun initData() {

        provinceItems.isNullOrEmpty().yes {
            queryAddress("0", 0)
        }
    }

    override fun onClick(v: View) {

        // 防止多次点击
        if (ViewUtils.isFastClick()) return
        binding?.let {

            if (it.selectCancelBtn === v) {
                dismiss()
            } else if (it.selectConfirmBtn === v) {
                var provinceId = ""
                var provinceName = ""
                var cityId = ""
                var cityName = ""
                var townshipId = ""
                var townshipName = ""

                provinceItem?.let { it1 ->
                    provinceId = it1.code
                    provinceName = it1.name
                }
                cityItem?.let { it1 ->
                    cityId = it1.code
                    cityName = it1.name
                }
                townshipItem?.let { it1 ->
                    townshipId = it1.code
                    if (townshipId == "-101") {
                        townshipName = ""
                        listener?.onAllNameClick("$provinceName$cityName")
                    } else {
                        townshipName = it1.name
                        listener?.onAllNameClick("$provinceName$cityName$townshipName")
                    }
                }

                listener?.onSuccessClick(
                    provinceId,
                    provinceName,
                    cityId,
                    cityName,
                    townshipId,
                    townshipName
                )
                dismiss()
            }
        }
    }

    /**
     * 回调接口
     */
    interface OnSelectAddressThreeLevelListener {
        fun onSuccessClick(
            provinceCode: String?,
            provinceName: String?,
            cityCode: String?,
            cityName: String?,
            areaCode: String?,
            areaName: String?,
        )

        fun onAllNameClick(provinceValue: String?)
    }

    /**
     * @param listener
     */
    fun setListener(listener: OnSelectAddressThreeLevelListener?) {
        this.listener = listener
    }

    /**
     * 查询省份
     */
    private fun queryAddress(mCode: String?, mLevel: Int = 0) {
        GlobalScope.launch {
            RxHttp.get("${CommonPurposeApi.COMMON_PUR_PST_ADDRESS}/${mCode}")
                .toAwait<ListCommon<BaseCityModel>>()
                .awaitResult {
                    it.isSuccess().yes {
                        doOnUiThread {
                            refreshProvinceData(it.Data, mLevel)
                        }
                    }.otherwise {
                        doOnUiThread {
                            ToastUtils.showToast(it.Message)
                        }
                    }
                }.onFailure {
                    doOnUiThread {
                        ToastUtils.showToast(it.message)
                    }
                }
        }
    }

    //条件选择器初始化
    private fun refreshProvinceData(mList: List<BaseCityModel>?, mLevel: Int = 0) {
        doOnUiThread {
            binding?.let {
                when (mLevel) {
                    1 -> {
                        cityItems.clear()
                        mList.isNullOrEmpty().yes {
                            cityItems.add(BaseCityModel("无", "无", "WU", "-101", "-101"))
                        }.otherwise {
                            cityItems.addAll(mList ?: arrayListOf())
                        }
                        it.cityWv.notifyDataSetChanged()

                        cityTemp.isNullOrEmpty().no {
                            for (i in cityItems.indices) {
                                if (cityItems[i].name == cityTemp) {
                                    // 请求的下级
                                    it.cityWv.currentItem = i// 初始化时显示的数据
                                    if (cityItems != null && cityItems.size > 0) {
                                        queryAddress(cityItems[i].code, 2)
                                        cityItem = cityItems[i]
                                    }
                                    break  // 结束遍历
                                }
                            }
                        }.otherwise {
                            it.cityWv.currentItem = 0// 初始化时显示的数据
                            if (cityItems != null && cityItems.size > 0) {
                                queryAddress(cityItems[0].code, 2)
                                cityItem = cityItems[0]
                            }
                        }
                    }

                    2 -> {
                        townshipItems.clear()
                        mList.isNullOrEmpty().yes {
                            townshipItems.add(BaseCityModel("无", "无", "WU", "-101", "-101"))
                        }.otherwise {
                            townshipItems.addAll(mList ?: arrayListOf())
                        }
                        it.townshipWv.notifyDataSetChanged()

                        townshipTemp.isNullOrEmpty().no {
                            for (i in townshipItems.indices) {
                                if (townshipItems[i].name == townshipTemp) {
                                    it.townshipWv.currentItem = i// 初始化时显示的数据
                                    if (townshipItems != null && townshipItems.size > 0) {
                                        townshipItem = townshipItems[0]
                                    }
                                    break  // 结束遍历
                                }
                            }
                        }.otherwise {
                            it.townshipWv.currentItem = 0// 初始化时显示的数据
                            if (townshipItems != null && townshipItems.size > 0) {
                                townshipItem = townshipItems[0]
                            } else {
                                townshipItem = null
                            }
                        }
                    }

                    else -> {
                        provinceItems.clear()
                        provinceItems.addAll(mList ?: arrayListOf())
                        it.provinceWv.notifyDataSetChanged()

                        provinceTemp.isNullOrEmpty().no {
                            for (i in provinceItems.indices) {
                                if (provinceItems[i].name == provinceTemp) {
                                    // 请求第一个省的下级
                                    if (provinceItems != null && provinceItems.size > 0) {
                                        it.provinceWv.currentItem = i// 初始化时显示的数据
                                        queryAddress(provinceItems[i].code, 1)
                                        provinceItem = provinceItems[i]
                                    }
                                    break  // 结束遍历
                                }
                            }
                        }.otherwise {
                            it.provinceWv.currentItem = 0// 初始化时显示的数据
                            // 请求第一个省的下级
                            if (provinceItems != null && provinceItems.size > 0) {
                                queryAddress(provinceItems[0].code, 1)
                                provinceItem = provinceItems[0]
                            }
                        }

                    }
                }

            }
        }
    }
}
